/*
 * Memcached.h
 *
 *  Created on: 2013. 11. 5.
 *      Author: the2
 */

#ifndef MEMCACHED_H_
#define MEMCACHED_H_

#include <libmemcached/memcached.h>
#include <string>

namespace ProjectZ {
namespace NLogic {

const char * const score		= "score_";
const char * const location		= "location_";
const char * const medal		= "medal_";

class MemcachedKey {

public:
	struct Data {
		std::string _score;
		std::string _location;
		std::string _medal;

		void Clear()
		{
			_score.clear();
			_location.clear();
			_medal.clear();
		}
	};

public:
	MemcachedKey();
	virtual ~MemcachedKey();

	void Initailize();

	void SetMemcachedKey(uint32_t userseq)
	{
		_pData->_score = score + std::to_string(userseq);
		_pData->_location = location + std::to_string(userseq);
		_pData->_medal = medal + std::to_string(userseq);
	}

	Data * GetData() { return _pData; }

private:
	Data * _pData;
};

class Memcached {
public:
	Memcached();
	virtual ~Memcached();

	bool Init(const char *address);
	bool Release();

	memcached_return_t Set( const char *key, const char *value, const size_t size, time_t expiration );
	char* Get( const char *key, size_t *valueLen, uint32_t *flags, memcached_return_t *error );

	memcached_return_t MGet( const char* const *keys, const size_t *key_length, size_t number_of_keys );
	char* Fetch( char *return_key, size_t *return_key_length, size_t *value_length, uint32_t *flags, memcached_return_t *error );

	memcached_return_t Delete( const char *key, size_t key_length, time_t expiration );
	const char* GetErrorString( memcached_return_t rc );

	memcached_return_t FlushAll();

private:
	memcached_st		* _pMemc;
	memcached_server_st	* _pServer;
};

#define MAX_RESULTSET				1048576 //1Mbyte
#define MAX_RESULTSET_FIELDSIZE		128


class MemResultSet
{
public:
	MemResultSet();
	virtual ~MemResultSet();

	bool	Init(short row, short field);
	bool	Init(const char *buff, int len);
	bool	Add(const char *item);
	bool	MoreRecord();

private:
	bool	AddShort(short *value);
	bool	AddString(const char *item);
	bool	Allocate();

public:
	char	m_Data[MAX_RESULTSET];
	char	**ROW;
	int		m_Offset;
	short	m_Fields;
	short	m_Rows;
	char	*m_pVal;

private:
	char	*m_pBuff;
	short	m_CurrentField;
	short	m_CurrentRow;
	bool	m_bIsFirstMoreRecord;
};

} /* namespace NLogic */
} /* namespace ProjectZ */

#endif /* MEMCACHED_H_ */
